package com.cn.zpark.filter;

import com.cn.zpark.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @PackageName: com.cn.zpark.filter
 * @ClassName: ResourcesFilter
 * @Description:
 * @author: RZS
 * @date: 2022/5/24  23:45
 */
@WebFilter("/view/*")
public class ResourcesFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 强转请求对象与响应对象
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 获取session对象
        HttpSession session = req.getSession();
        // 从session对象中获取绑定user数据
        User user = (User) session.getAttribute("user");

        // 判断user是否有数据
        if(user == null){
            // 没有登录，重定向到登陆页面
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
        }else {
            // 用户已经登录，可正常访问后续页面
            chain.doFilter(req, resp);
        }
    }

    @Override
    public void destroy() {
    }
}
